<template>
  <div class="app-container">
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="440px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
        style="margin-left: 55px"
      >
        <el-col :span="24">
          <el-form-item label="变更单号" prop="bgDjbh">
            <el-input
              v-model="queryParams.bgDjbh"
              placeholder="请输入变更单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="状态标志" prop="bgZtbz">
            <el-select
              v-model="queryParams.bgZtbz"
              placeholder="请选择状态标志"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in bgZtbzOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              clearable
              size="small"
              v-model="queryParams.createTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择创建时间"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <el-row :gutter="10" style="position: relative; margin-bottom: 5px">
      <el-col :span="18" style="display: flex; align-items: flex-start">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearchs"
          >搜索</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:bg:add']"
          >新增</el-button
        >
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:bg:edit']"
        >
          修改
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleSubmit"
          v-hasPermi="['project:bg:submit']"
        >
          提交
        </el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleCancellation"
          v-hasPermi="['project:bg:cancellation']"
        >
          作废
        </el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['project:bg:export']"
        >
          导出
        </el-button>
        <Tag type="dot" color="#a8ace0">作废</Tag>
        <Tag type="dot" color="#0cd12d">提交</Tag>
        <Tag type="dot" color="#bb0331">通过</Tag>
      </el-col>
      <el-col :span="6" style="text-align: right">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <split-pane
      :min-percent="10"
      :default-percent="50"
      split="horizontal"
      style="height: calc(100vh - 200px)"
    >
      <template #paneL>
        <el-table
          v-loading="loading"
          :data="bgList"
          border
          stripe
          :row-style="{ padding: '0px' }"
          :cell-style="iCellStyle"
          :header-row-style="{ padding: '2px' }"
          :header-cell-style="{ 'text-align': 'center', padding: '2px' }"
          highlight-current-row
          height="100%"
          ref="multipleTable"
          @selection-change="handleSelectionChange"
          @row-click="getChildList"
        >
          <el-table-column label="#" type="index" width="55" align="center" />
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="变更单号"
            :show-overflow-tooltip="true"
            width="140"
            align="center"
            prop="bgDjbh"
          />
          <el-table-column
            label="ECN单号"
            :show-overflow-tooltip="true"
            width="120"
            align="center"
            prop="bgEcnno"
          />
          <el-table-column
            label="备注"
            :show-overflow-tooltip="true"
            align="center"
            prop="remark"
          />
          <el-table-column
            label="作废理由"
            :show-overflow-tooltip="true"
            align="center"
            prop="bgNgdesc"
          />
          <el-table-column
            label="撤回理由"
            :show-overflow-tooltip="true"
            align="center"
            prop="bgRollbackDesc"
          />
          <el-table-column
            label="创建人员"
            align="center"
            width="80"
            prop="createBy"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="更改人员"
            align="center"
            width="80"
            prop="updateBy"
          />
          <el-table-column
            label="更改时间"
            align="center"
            prop="updateTime"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="审核人员"
            align="center"
            width="80"
            prop="bgShry"
          />
          <el-table-column
            label="审核日期"
            align="center"
            prop="bgShrq"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.bgShrq, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="120"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                :disabled="
                  bgdDjbh.bgZtbz === '2' ||
                  bgdDjbh.bgZtbz === '3' ||
                  bgdDjbh.bgTjflag === '1'
                "
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleChange(scope.row)"
                v-hasPermi="['project:bg:change']"
              >
                添加变更
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #paneR>
        <el-table
          v-loading="loading"
          size="mini"
          border
          stripe
          :row-style="{ padding: '0px' }"
          :cell-style="{ padding: '0px' }"
          :header-row-style="{ padding: '2px' }"
          :header-cell-style="{ 'text-align': 'center', padding: '2px' }"
          highlight-current-row
          :data="bgdList"
          height="100%"
        >
          <el-table-column label="#" type="index" width="55" align="center" />
          <el-table-column
            label="变更类型"
            width="80"
            align="center"
            prop="bgdType"
          >
            <template #default="scope">
              <dict-tag :options="bgStyleOptions" :value="scope.row.bgdType" />
            </template>
          </el-table-column>
          <el-table-column
            label="父项代码"
            :show-overflow-tooltip="true"
            width="130"
            align="center"
            prop="bgdFxdm"
          />
          <el-table-column
            label="父项品名规格"
            width="300"
            :show-overflow-tooltip="true"
            prop="bgdFxdmPmgg"
          />
          <el-table-column
            label="子项代码"
            width="130"
            align="center"
            prop="bgdZxdm"
          />
          <el-table-column
            label="子项品名规格"
            width="240"
            :show-overflow-tooltip="true"
            prop="bgdZxdmPmgg"
          />
          <el-table-column
            label="替换代码"
            width="130"
            align="center"
            prop="bgdReplaceZxdm"
          />
          <el-table-column
            label="替换品名规格"
            width="240"
            align="center"
            prop="bgdReplaceZxdmPmgg"
          />
          <el-table-column label="采购属性" align="center" prop="bgdCgsx">
            <template #default="scope">
              <dict-tag :options="bomCgsxOptions" :value="scope.row.bgdCgsx" />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80" align="center" prop="bgdDw">
            <template #default="scope">
              <dict-tag :options="itmDwOptions" :value="scope.row.bgdDw" />
            </template>
          </el-table-column>
          <el-table-column
            label="主成型标识"
            width="100"
            align="center"
            prop="bgdMain"
          >
            <template #default="scope">
              <dict-tag :options="bodWwbzOptions" :value="scope.row.bgdMain" />
            </template>
          </el-table-column>
          <el-table-column label="单位用量" align="center" prop="bgdDwyl" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建人员" align="center" prop="createBy" />
          <el-table-column
            label="操作"
            align="center"
            width="120"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                :disabled="bgdDjbh.bgZtbz === '2'"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDeleteBgd(scope.row)"
                v-hasPermi="['project:bg:remove']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </split-pane>

    <!-- 添加或修改bom资料变更对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="变更单号" prop="bgDjbh">
          <el-input v-model="form.bgDjbh" disabled />
        </el-form-item>
        <el-form-item label="ECN单号" prop="bgEcnno">
          <el-input v-model="form.bgEcnno" placeholder="请输入ECN单号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加变更-->
    <el-dialog
      :title="title"
      v-model="change"
      :close-on-click-modal="false"
      draggable
      width="800px"
      append-to-body
    >
      <el-form
        ref="bgdForm"
        :model="bgdForm"
        label-width="100px"
        :rules="bgdRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="变更单号" prop="bgDjbh">
              <el-input v-model="bgdForm.bgdDjbh" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ECN单号" prop="bgdEcnno">
              <el-input v-model="bgdForm.bgdEcnno" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="变更类型" prop="bgdType">
          <el-radio-group v-model="bgdForm.bgdType">
            <el-radio
              v-for="dict in bgStyleOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >
              {{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row v-if="bgdForm.bgdType !== 'updatebat'">
          <el-col :span="12">
            <el-form-item label="父项代码" prop="bgdFxdm">
              <el-select
                v-model="bgdForm.bgdFxdm"
                :filter-method="getWldmListFXTOP50"
                @change="getBgdFxdm"
                filterable
                placeholder="请选择父项代码"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in FXwldmList"
                  :label="dict.itmWldm"
                  :key="dict.itmWldm"
                  :value="dict.itmWldm"
                />
              </el-select>
              <!--              <el-input v-model="bgdForm.bgdFxdm" @blur="getBgdFxdm"  placeholder="必填" />-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父项品名规格" prop="bgdFxdmPmgg">
              <el-select
                v-model="bgdForm.bgdFxdmPmgg"
                filterable
                remote
                value-key="itmPmgg"
                clearable
                placeholder="请输入关键词"
                @change="changeFxpm"
                :remote-method="remoteMethod"
                :loading="loadingPmgg"
                style="width: 280px"
              >
                <el-option
                  v-for="item in optionsPmgg"
                  :key="item.itmWldm"
                  :label="item.itmPmgg"
                  :value="item"
                ></el-option>
              </el-select>
              <!-- <el-input v-model="bgdForm.bgdFxdmPmgg" disabled /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="子项代码" prop="bgdZxdm">
              <el-select
                v-model="bgdForm.bgdZxdm"
                :filter-method="getWldmListZXTOP50"
                @change="getBgdZxdmm"
                filterable
                placeholder="请选择子项代码"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in ZXwldmList"
                  :label="dict.itmWldm"
                  :key="dict.itmWldm"
                  :value="dict.itmWldm"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="子项品名规格" prop="bgdZxdmPmgg">
              <el-select
                v-model="bgdForm.bgdZxdmPmgg"
                filterable
                remote
                value-key="itmPmgg"
                clearable
                placeholder="请输入关键词"
                @change="changeZxpm"
                :remote-method="remoteMethod"
                :loading="loadingPmgg"
                style="width: 280px"
              >
                <el-option
                  v-for="item in optionsPmgg"
                  :key="item.itmWldm"
                  :label="item.itmPmgg"
                  :value="item"
                ></el-option>
              </el-select>
              <!-- <el-input v-model="bgdForm.bgdZxdmPmgg" disabled /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="bgdForm.bgdType === 'replace'"
              label="替换代码"
              prop="bgdReplaceZxdm"
            >
              <el-select
                v-model="bgdForm.bgdReplaceZxdm"
                :filter-method="getWldmListFXTOP50"
                @change="getBgdReplaceZxdm"
                filterable
                placeholder="请选择替换代码"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in FXwldmList"
                  :label="dict.itmWldm"
                  :key="dict.itmWldm"
                  :value="dict.itmWldm"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              v-if="bgdForm.bgdType === 'replace'"
              label="替换品名规格"
              prop="bgdReplaceZxdmPmgg"
            >
              <el-select
                v-model="bgdForm.bgdReplaceZxdmPmgg"
                filterable
                remote
                value-key="itmPmgg"
                clearable
                placeholder="请输入关键词"
                @change="changeThpm"
                :remote-method="remoteMethod"
                :loading="loadingPmgg"
                style="width: 280px"
              >
                <el-option
                  v-for="item in optionsPmgg"
                  :key="item.itmWldm"
                  :label="item.itmPmgg"
                  :value="item"
                ></el-option>
              </el-select>
              <!-- <el-input v-model="bgdForm.bgdReplaceZxdmPmgg" disabled /> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          v-if="bgdForm.bgdType !== 'delete' && bgdForm.bgdType !== 'updatebat'"
          label="单位用量"
          prop="bgdDwyl"
        >
          <el-input v-model="bgdForm.bgdDwyl" placeholder="必填" />
        </el-form-item>
        <el-form-item
          v-if="bgdForm.bgdType !== 'delete'"
          label="采购属性"
          prop="bgdCgsx"
        >
          <el-select
            v-model="bgdForm.bgdCgsx"
            placeholder="请选择采购属性"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in bomCgsxOptionsNromal"
              :key="dict.cgId"
              :label="dict.cgName"
              :value="dict.cgId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="主成型标识"
          prop="bgdMain"
          v-if="bgdForm.bgdType !== 'updatebat'"
        >
          <el-radio-group v-model="bgdForm.bgdMain">
            <el-radio
              v-for="dict in bodWwbzOptions"
              :key="dict.dictId"
              :label="dict.dictValue"
            >
              {{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="变更备注" prop="remark">
          <el-input v-model="bgdForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBgdForm">取 消</el-button>
        <el-button type="primary" @click="submitBgdForm">确 定</el-button>
      </div>
    </el-dialog>

    <!--  作废对话框  -->
    <el-dialog
      :title="title"
      v-model="cancellationView"
      :close-on-click-modal="false"
      draggable
      width="600px"
      append-to-body
    >
      <el-form
        ref="cancellationForm"
        :model="form"
        :rules="cancellationFormRules"
        label-width="100px"
      >
        <el-form-item label="作废理由" prop="bgNgdesc">
          <el-input v-model="form.bgNgdesc" placeholder="请输入作废理由" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelCancellation">取 消</el-button>
        <el-button type="primary" @click="submitCancellationForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBg,
  getBg,
  delBg,
  addBg,
  updateBg,
  exportBg,
  submitBg,
  cancellationBg,
  submitBgd,
  findBodDets,
  deleteBgd,
} from "@/api/project/bg";
import { getAllCgList, getAllCgListNormal } from "@/api/project/mstr";
import {
  selectItmByWldm,
  getItmWldmList,
  getItmWldmAndCustWldmList,
  getItmByInfo,
} from "@/api/project/materiel";
import { getBomByOrders, judge, JudgeParentWithChild } from "@/api/project/bom";

export default {
  name: "Bg",
  data() {
    return {
      tableH: 1,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //所有采购
      bomCgsxOptions: [],
      //有效采购属性
      bomCgsxOptionsNromal: [],
      bodWwbzOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // bom资料变更表格数据
      bgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSearch: false,

      //当前选中数据
      currentData: [],

      //单位
      itmDwOptions: [],

      //详情表
      bgdList: [],

      //保存当前订单
      bgdDjbh: null,

      //作废框
      cancellationView: false,

      bgdForm: {
        bgdId: null,
        bgdDjbh: null,
        bgdType: "add",
        bgdFxdm: null,
        bgdZxdm: null,
        bgdDwyl: null,
        bgdCgsx: null,
        bgdMain: null,
        remark: null,
        createBy: null,
        createTime: null,
        bgdEcnno: null,
        bgdReplaceZxdm: null,
        bgdFxdmPmgg: null,
        bgdZxdmPmgg: null,
        bgdReplaceZxdmPmgg: null,
      },
      //添加变更弹窗
      change: false,
      // 状态标志字典
      bgZtbzOptions: [],

      // 只显示前50条物料list
      FXwldmList: [],
      ZXwldmList: [],
      optionsPmgg: [],
      loadingPmgg: false,
      // 全部的物料list
      itmwldmOptionsDatas: [],

      //类型字典
      bgStyleOptions: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bgDjbh: null,
        bgZtbz: "1",
        createTime: null,
        bgTjflag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      cancellationFormRules: {
        bgNgdesc: [
          { required: true, message: "作废理由不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    bgdRules() {
      let rule = {
        bgdFxdm: [
          { required: true, message: "父项代码不能为空", trigger: "blur" },
        ],
        bgdZxdm: [
          { required: true, message: "子项代码不能为空", trigger: "blur" },
        ],
        bgdDwyl: [
          { required: true, message: "单位用量不能为空", trigger: "blur" },
          {
            pattern: /^\d+$|^\d*\.\d+$/,
            message: "单位用量必须大于0",
            trigger: "blur",
          },
        ],
        bgdCgsx: [
          { required: true, message: "采购属性不能为空", trigger: "change" },
        ],
      };

      switch (this.bgdForm.bgdType) {
        case "replace":
          rule.bgdReplaceZxdm = [
            {
              required: true,
              message: "替换子项代码不能为空",
              trigger: "blur",
            },
          ];
          break;
        case "delete":
          delete rule.bgdType;
          delete rule.bgdCgsx;
          break;
        case "updatebat":
          delete rule.bgdFxdm;
      }
      return rule;
    },
  },
  created() {
    this.getDicts("sys_flag").then((response) => {
      this.bodWwbzOptions = response.data;
    });
    getItmWldmAndCustWldmList().then((res) => {
      this.itmwldmOptionsDatas = res.data;
    });
    this.getDicts("sys_bom_bg_ztbz").then((response) => {
      this.bgZtbzOptions = response.data;
    });
    this.getDicts("sys_unit").then((response) => {
      this.itmDwOptions = response.data;
    });
    this.getDicts("sys_bom_bg_style").then((response) => {
      this.bgStyleOptions = response.data;
    });
    getAllCgList().then((response) => {
      this.bomCgsxOptions = response.data;
      for (let i of this.bomCgsxOptions) {
        i.dictLabel = i.cgName;
        i.dictValue = i.cgId + "";
        i.listClass = "default";
      }
    });
    getAllCgListNormal().then((response) => {
      this.bomCgsxOptionsNromal = response.data;
      for (let i of this.bomCgsxOptionsNromal) {
        i.dictLabel = i.cgName;
        i.dictValue = i.cgId + "";
        i.listClass = "default";
      }
    });
    this.getList();
  },
  methods: {
    iCellStyle({ row, column, rowIndex, columnIndex }) {
      //提交状态
      if (row.bgTjflag == "1" && row.bgZtbz == 1) {
        return "color:#0cd12d";
      }
      //通过状态
      else if (row.bgTjflag == "1" && row.bgZtbz == 2) {
        return "color:#bb0331";
      }
      //作废状态
      else if (row.bgZtbz == 3) {
        return "color:#a8ace0";
      } else {
      }
    },

    /** 查询bom资料变更列表 */
    getList(row) {
      this.loading = true;
      this.tableH = (document.body.clientHeight - 160) / 2;
      this.queryParams.pageSize = this.tableH > 350 ? 15 : 10;
      listBg(this.queryParams).then((response) => {
        this.bgList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.bgdList = [];
        if (row) {
          this.getChildList(row);
        } else {
          if (this.bgList != null && this.bgList.length > 0) {
            this.getChildList(this.bgList[0]);
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset()
      this.openSearch = false;
    },
    cancelCancellation() {
      this.cancellationView = false;
      // this.reset()
    },
    cancelBgdForm() {
      this.change = false;
      // this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        bgId: null,
        bgDjbh: null,
        bgEcnno: null,
        bgZtbz: null,
        bgTjflag: null,
        remark: null,
        bgNgdesc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        bgShry: null,
        bgShrq: null,
      };
      this.resetForm("form");

      // this.bgdForm = {
      //   bgdId: null,
      //   bgdDjbh: null,
      //   bgdType: 'add',
      //   bgdFxdm: null,
      //   bgdZxdm: null,
      //   bgdDwyl: null,
      //   bgdCgsx: null,
      //   bgdMain: null,
      //   remark: null,
      //   createBy: null,
      //   createTime: null,
      //   bgdEcnno: null,
      //   bgdReplaceZxdm: null,
      //   bgdFxdmPmgg: null,
      //   bgdZxdmPmgg: null,
      //   bgdReplaceZxdmPmgg: null,
      // }

      // this.resetForm('bgdForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.currentData = selection;
      this.ids = selection.map((item) => item.bgId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加bom资料变更";
    },
    handleSearchs() {
      this.reset();
      this.title = "查询bom资料维护";
      this.openSearch = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bgId = row.bgId || this.ids;
      getBg(bgId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改bom资料变更";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.bgId != null) {
            if (this.form.bgZtbz == 2) {
              this.msgError(this.form.bgDjbh + "已经审核，禁止修改");
              return;
            }
            if (this.form.bgZtbz == 3) {
              this.msgError(this.form.bgDjbh + "已经作废，禁止修改");
              return;
            }
            if (this.form.bgTjflag == 1) {
              this.msgError(this.form.bgDjbh + "已经提交，禁止修改");
              return;
            }
            updateBg(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBg(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bgIds = row.bgId || this.ids;
      this.$confirm(
        '是否确认删除bom资料变更编号为"' + bgIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delBg(bgIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有bom资料变更数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportBg(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },

    /*提交审核*/
    handleSubmit() {
      //作废的单据不可以再审核

      for (let i of this.currentData) {
        if (i.bgTjflag == 1) {
          this.msgError(i.bgDjbh + "已经提交，禁止重复提交");

          return;
        }

        if (i.bgZtbz == 2) {
          this.msgError(i.bgDjbh + "已经审核，禁止重复审核");

          return;
        }

        if (i.bgZtbz == 3) {
          this.msgError(i.bgDjbh + "已经作废，禁止提交");

          return;
        }
      }

      const bgIds = this.ids;
      this.$confirm("是否确认提交?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return submitBg(bgIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("提交成功");
        })
        .catch(() => {});
    },
    /*作废*/
    handleCancellation() {
      //已经审核的单据不能作废
      for (let i of this.currentData) {
        if (i.bgZtbz === "2") {
          this.msgError(i.bgDjbh + "已经审核，禁止作废");

          return;
        }
      }
      this.$confirm("是否确认作废单据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {})
        .then(() => {
          this.cancellationView = true;
          this.title = "请填写作废理由";
        })
        .catch(() => {});
    },

    submitCancellationForm() {
      this.$refs["cancellationForm"].validate((valid) => {
        if (valid) {
          cancellationBg(this.ids, this.form.bgNgdesc).then((response) => {
            this.msgSuccess("作废成功");
            this.cancellationView = false;
            this.getList();
          });
        }
      });
    },

    //查询子项
    getChildList(row) {
      //点击行触发，选中或不选中复选框
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
      this.bgdDjbh = row;

      if (row.bgDjbh != null) {
        findBodDets(row.bgDjbh).then((response) => {
          this.bgdList = response.data;
        });
      }
    },
    /*显示变更*/
    handleChange(row) {
      this.getWldmListFXTOP50("");
      this.getWldmListZXTOP50("");

      this.title = "bom资料变更";
      this.reset();

      //赋值
      this.bgdForm.bgdDjbh = row.bgDjbh;
      this.bgdForm.bgdEcnno = row.bgEcnno;

      //显示框
      this.change = true;
    },

    getWldmListFXTOP50(input) {
      let temp = [];
      let that = this;
      new Promise(function (resolve, reject) {
        for (let i of that.itmwldmOptionsDatas) {
          if (i.itmWldm.indexOf(input) != -1) {
            temp.push(i);
          }
        }
        resolve(temp);
      }).then((res) => {
        that.FXwldmList = res.slice(0, 50);
      });
    },
    getWldmListZXTOP50(input) {
      let temp = [];
      let that = this;
      new Promise(function (resolve, reject) {
        for (let i of that.itmwldmOptionsDatas) {
          if (i.itmWldm.indexOf(input) != -1) {
            temp.push(i);
          }
        }
        resolve(temp);
      }).then((res) => {
        that.ZXwldmList = res.slice(0, 50);
      });
    },
    //获取父项代码
    getBgdFxdm(val) {
      if (val) {
        getBomByOrders(val).then((res1) => {
          if (res1.data) {
            this.bgdForm.bgdFxdmPmgg = res1.data.itmPmgg;
            this.getBgdZxdmm();
          } else {
            this.msgError("Bom无此父项物料");
            this.bgdForm.bgdFxdmPmgg = "";
          }
        });
      } else {
        this.bgdForm.bgdFxdmPmgg = "";
      }
    },

    //获取子项代码
    getBgdZxdmm(val) {
      this.$nextTick((val) => {
        if (this.bgdForm.bgdZxdm) {
          if (this.bgdForm.bgdType === "replace") {
            //如果是替换变更，则查询其子项是否存在

            if (!this.bgdForm.bgdFxdm) {
              this.msgError("请填写父项物料");
              this.bgdForm.bgdZxdmPmgg = "";
              return;
            }
            JudgeParentWithChild(
              this.bgdForm.bgdFxdm,
              this.bgdForm.bgdZxdm
            ).then((res2) => {
              if (!res2.data) {
                this.bgdForm.bgdZxdmPmgg = "";
                this.msgError("该父项物料代码无此子项物料代码");
              } else {
                selectItmByWldm(this.bgdForm.bgdZxdm).then((res3) => {
                  if (res3.data) {
                    this.bgdForm.bgdZxdmPmgg = res3.data.itmPmgg;
                  } else {
                    this.bgdForm.bgdZxdmPmgg = "";
                    this.msgError("系统无此物料");
                  }
                });
              }
            });
          } else {
            selectItmByWldm(this.bgdForm.bgdZxdm).then((response) => {
              if (response.data) {
                this.bgdForm.bgdZxdmPmgg = response.data.itmPmgg;
              } else {
                this.bgdForm.bgdZxdmPmgg = "";
                this.msgError("系统无此物料");
              }
            });
          }
        } else {
          this.bgdForm.bgdZxdmPmgg = "";
        }
      });
    },
    remoteMethod(query) {
      if (query !== "") {
        this.loadingPmgg = true;
        getItmByInfo({ itmPmgg: query, pageSize: 30 }).then((res) => {
          console.log(res);
          this.optionsPmgg = res.rows.slice(0, 50);
          this.loadingPmgg = false;
        });
      } else {
        this.optionsPmgg = [];
      }
    },
    changeFxpm(val) {
      this.bgdForm.bgdFxdm = val.itmWldm;
      this.getBgdFxdm(val.itmWldm);
    },
    changeZxpm(val) {
      this.bgdForm.bgdZxdm = val.itmWldm;
      this.getBgdZxdmm(val.itmWldm);
    },
    changeThpm(val) {
      this.bgdForm.bgdReplaceZxdm = val.itmWldm;
      this.getBgdReplaceZxdm(val.itmWldm);
    },

    //获取替换代码
    getBgdReplaceZxdm() {
      if (this.bgdForm.bgdReplaceZxdm) {
        selectItmByWldm(this.bgdForm.bgdReplaceZxdm).then((response) => {
          if (response.data) {
            this.bgdForm.bgdReplaceZxdmPmgg = response.data.itmPmgg;
          } else {
            this.msgError("系统无此物料");
            this.bgdForm.bgdReplaceZxdmPmgg = "";
          }
        });
      } else {
        this.bgdForm.bgdReplaceZxdmPmgg = "";
      }
    },

    //提交表单
    submitBgdForm() {
      this.$refs["bgdForm"].validate((valid) => {
        if (valid) {
          //拿到数据
          if (this.bgdForm.bgdType === "replace") {
            judge(
              this.bgdForm.bgdFxdm,
              this.bgdForm.bgdReplaceZxdm,
              this.bgdForm.bgdCgsx
            ).then((response) => {
              if (response.data) {
                //提交
                submitBgd(this.bgdForm).then((response) => {
                  this.msgSuccess("提交成功");
                  this.change = false;
                  this.getList();
                });
              } else {
                this.msgError("一个Bom结构只允许出现一个成型物料");
              }
            });
          } else {
            this.bgdForm.bgdReplaceZxdm = null;
            this.bgdForm.bgdReplaceZxdmPmgg = null;
            if (
              this.bgdForm.bgdType === "delete" ||
              this.bgdForm.bgdType === "updatebat"
            ) {
              if (this.bgdForm.bgdType === "updatebat") {
                this.bgdForm.bgdFxdm = null;
                this.bgdForm.bgdFxdmPmgg = null;
              }
              //提交
              submitBgd(this.bgdForm).then((response) => {
                this.msgSuccess("提交成功");
                this.change = false;
                this.getList();
              });
            } else {
              judge(
                this.bgdForm.bgdFxdm,
                this.bgdForm.bgdZxdm,
                this.bgdForm.bgdCgsx
              ).then((response) => {
                if (response.data) {
                  //提交
                  submitBgd(this.bgdForm).then((response) => {
                    this.msgSuccess("提交成功");
                    this.change = false;
                    this.getList();
                  });
                } else {
                  this.msgError("一个Bom结构只允许出现一个成型物料");
                }
              });
            }
          }
        }
      });
    },

    //删除子项
    handleDeleteBgd(row) {
      const bgdIds = row.bgdId;
      this.$confirm("是否确认删除该数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return deleteBgd(bgdIds);
        })
        .then(() => {
          this.getList(this.bgdDjbh);
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
